import Util from '../../utils/util.js';
import {createOrder, getDeliverTimeList, orderPay} from "../../api/order";
import {getAddressDetail} from "../../api/member";
import {getShopDetail} from "../../api/shop";

const app = getApp()
Page({

  data: {
    nav_select: false, // 快捷导航
    options: {}, // 当前页面参数

    address: null, // 默认收货地址
    exist_address: false, // 是否存在收货地址

    goods: {}, // 商品信息

    disabled: false,
    hasError: false,
    error: '',
    cartList: {},
    remark: "",

    order_source: false, // 是否代下单

    btnActive: true,
    out_trade_no: "",

    curIndex: 0,
    deliveryTimeDialog: false, //订单配送时间
    deliveryTimeList: [], // 配送时间列表
    timeIdx: -1,
    delivery_time: '',
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    const that = this;

    // 当前页面参数
    this.data.options = options;
    Util.chekWxLogin().then(res => {
      // that.showDeliveryTime();
      let current = Util.getStorageInfo("current_menu");
      if (!Util.isEmpty(current)) {
        current['currentDay'] = Util.formatTime(4, current['date']);
        current['currentWeek'] = Util.getWeek(current['date']);
      }
      this.setData({
        current_menu: current,
        userInfo: res.userInfo,
        cartKey: wx.getStorageSync("cartKey") || null
      })

      const cartList = Util.getCartList()
      if (Util.isEmpty(cartList) || Util.isEmpty(cartList[that.data.cartKey])) {
        return Util.Tips({title: "暂无商品，请先选择商品",}, {tab: 1, url: "../index/index"})
      }
      this.setData({
        cartList: cartList[that.data.cartKey],
        cartLists: cartList //购物车集合
      })

      if (!Util.isEmpty(this.data.current_menu)) {
        wx.showLoading({
          title: "正在加载..."
        })
        getShopDetail(this.data.current_menu.shop_id).then(res => {
          that.setData({
            shop: res.data
          })
          that.cartStat();
        }).catch(errmsg => {
          Util.Tips({title: errmsg})
        }).finally(() => {
          wx.hideLoading()
        })
      } else {
        that.cartStat();
      }

      that.getAddressInfo();
    }).then(() => {
      this.onLoadTabbar();
    }).catch(errmsg => {
      return Util.Tips({title: errmsg})
    })

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    const address_id = wx.getStorageSync("address_id");
    if (!Util.isEmpty(address_id)) {
      this.setData({
        address_id: address_id
      })
      wx.removeStorageSync("address_id")
      this.getAddressInfo();
    }
  },

  selectNav: function (t) {
    let curNav = t.target.dataset.id,
      curIndex = parseInt(t.target.dataset.index);

    //判断是否是套餐
    this.setData({
      curIndex: curIndex,
      timeIdx: -1
    });
  },

  selectTime(e) {
    const that = this,
      skey = e.currentTarget.dataset.skey,
      deliveryTimeList = that.data.deliveryTimeList || [];
    this.setData({
      delivery_time: deliveryTimeList[this.data.curIndex].timeList[skey],
      deliveryTimeList: deliveryTimeList,
      timeIdx: skey,
      deliveryTimeDialog: false,
    })
  },

  closeLayer(e) {
    this.setData({
      deliveryTimeDialog: false,
      timeIdx: -1,
    })
  },

  showDeliveryTime(e) {
    this.setData({
      deliveryTimeDialog: true
    })
    const deliveryTimeList = this.data.deliveryTimeList || [];

    if (Util.isEmpty(deliveryTimeList) || deliveryTimeList.length == 0) {
      wx.showLoading({
        title: "正在加载..."
      })
      getDeliverTimeList({shop_id: this.data.shop.id || ''}).then(res => {
        let deliveryTimeList = res.data || [];
        if (deliveryTimeList.length > 0) {
          deliveryTimeList[0].active = true;
        }
        this.setData({
          deliveryTimeList: deliveryTimeList,
          curIndex: 0,
        })
      }).finally(() => {
        wx.hideLoading()
      })
    }
  },
  //获取默认地址
  getAddressInfo() {
    const that = this;
    getAddressDetail(this.data.address_id || '').then(res => {

      that.setData({
        address: res.data.address || "",
        member: res.data.member || null,
        exist_address: !Util.isEmpty(res.data.address)
      })

    }).catch(errmsg => {
      app.Tips({title: errmsg})
    })
  },

  inputName(e) {
    this.setData({remark: e.detail.value});
  },

  cartStat() {
    const carts = this.data.cartList;
    if (Util.isEmpty(carts)) {
      return;
    }

    let total_price = 0, total_amount = 0, bag_price = 0;
    for (const k in carts) {
      let product = carts[k];

      if (Util.isEmpty(product)) {
        continue;
      }
      /*
      total_price += (carts[k].total_price || carts[k].price || 0.0) * carts[k].amount
      total_amount += carts[k].amount;
      bag_price += (parseFloat(carts[k].bag_price) * (carts[k].amount || 1)) || 0;
      */
      if (product.items) {
        product.items.map((e1, k1) => {
          bag_price += (parseFloat(product.bag_price) * (e1.amount || 1)) || 0;
          total_price += parseFloat(e1.total_price || product.price || 0.0) * e1.amount;
          total_amount += e1.amount;
        })
      } else {
        total_price += parseFloat(product.total_price || product.price || 0.0) * product.amount;
        total_amount += product.amount;
        bag_price += (parseFloat(product.bag_price) * (product.amount || 1)) || 0;
      }
    }

    let shipping_price = Util.getShopShippingPrice(total_amount, this.data.shop.base_shipping_price);
    total_price = total_price + shipping_price;

    this.setData({
      shipping_price: shipping_price,
      bag_price: bag_price.toFixed(1),
      cartTotal: {
        amount: Object.keys(carts).length,
        total_price: (total_price + bag_price).toFixed(1)
      }
    })
  },

  /**
   * 选择收货地址
   */
  selectAddress: function () {
    wx.navigateTo({
      url: '../address/' + (this.data.exist_address ? 'index?from=flow' : 'create')
    });
  },

  /**
   * 订单提交
   */
  submitOrder: function (e) {
    const that = this,
      cartList = this.data.cartList,
      order_source = this.data.order_source || 0;

    //已创建不再直接支付
    if (!Util.isEmpty(this.data.out_trade_no)) {
      this._goPay(this.data.out_trade_no)
      return;
    }

    let formData = {}, products = [];
    for (const k in cartList) {
      if (!Util.isEmpty(cartList[k].items)) {
        cartList[k].items.map((e1, k1) => {
          let skus = [];
          e1.skus.map((e2, k2) => {
            skus.push({
              id: e2.id,
              amount: e2.cart_amount || e2.amount || 1,
            })
          })

          products.push({
            id: cartList[k].id,
            amount: e1.amount || 0,
            skus: skus,
          })
        })
      } else {
        products.push({
          id: cartList[k].id,
          amount: cartList[k].amount || 0,
          skus: []
        })
      }
    }

    if (Util.isEmpty(products)) {
      return Util.Tips({
        title: "暂无商品，请先选择商品",
        hideMask: true,
      }, {
        tab: 1,
        url: "../index/index"
      })
    }
    formData['products'] = products;
    if (!that.data.btnActive) {
      return false;
    }
    if (!this.data.address['id']) {
      return Util.Tips({title: "收货地址必填"})
    }

    //单店需要选择配送时间
    if (parseInt(this.data.shop.type) == 0) {

      if (this.data.timeIdx == -1) {
        return Util.Tips({title: "请选择送达时间", hideMask: true});
      }
      formData['delivery_time'] = this.data.deliveryTimeList[this.data.curIndex].date + ' ' + this.data.deliveryTimeList[this.data.curIndex].timeList[this.data.timeIdx];
    } else {
      formData['delivery_time'] = '';
    }

    formData['type'] = "buyer";
    formData['address_id'] = this.data.address['id'];
    formData['shop_id'] = that.data.shop.id || 0;

    if (!Util.isEmpty(that.data.current_menu)) {
      formData['menu_id'] = this.data.current_menu.id || "";
    }

    if (!Util.isEmpty(this.data.shop) && this.data.shop.is_remark == 1) {
      formData['remark'] = this.data.remark;
    }

    formData['order_source'] = order_source == true ? 1 : 0;
    wx.showLoading({
      title: '正在提交..',
    })
    that.setData({btnActive: false})

    createOrder(formData).then(result => {
      //清空缓存
      let cartLists = that.data.cartLists || [];
      if (!Util.isEmpty(cartLists[that.data.cartKey])) {
        delete cartLists[that.data.cartKey];
        wx.removeStorageSync('cartKey')
        if (Util.isEmpty(cartLists)) {
          wx.removeStorageSync("carts");
        } else {
          wx.setStorageSync("carts", JSON.stringify(cartLists));
        }
      }

      const out_trade_no = result.data.out_trade_no || "";
      that.setData({
        out_trade_no: out_trade_no
      })
      if (!Util.isEmpty(result.data.status) && result.data.status === 10) {
        return Util.Tips({
          title: "支付成功",
          icon: "success",
          hideMask: true
        }, {
          tab: 5,
          url: "../order/detail?order_id=" + out_trade_no
        })
      }

      // 判断是否要付款
      if (!Util.isEmpty(result.data.order_source) && result.data.order_source === 1) {
        wx.setStorageSync('is_refresh', 1)
        wx.switchTab({url: "../member/index"})
        return;
      }

      if (out_trade_no) {
        that._goPay(out_trade_no);
      }
    }).catch(errmsg => {
      Util.Tips({title: errmsg})
    }).finally(() => {
      that.setData({btnActive: true});
      wx.hideLoading();
    })

  },

  changeSwitch(e) {
    this.setData({
      [e.currentTarget.dataset.key]: !this.data.order_source
    })
  },

  _goPay(out_trade_no) {
    if (Util.isEmpty(out_trade_no))
      return Util.Tips({title: "订单异常"});

    const that = this;
    orderPay({order_id: out_trade_no})
      .then(res => {
        let data = res.data

        wx.requestPayment({
          'timeStamp': data.timeStamp,
          'nonceStr': data.nonceStr,
          'package': data.package,
          'signType': 'MD5',
          'paySign': data.paySign,
          success: function (res) {
            wx.hideLoading()
            wx.setStorageSync('is_refresh', 1)

            return Util.Tips({
              title: "支付成功",
              icon: "success",
              hideMask: true
            }, {
              tab: 5,
              url: "../order/result?order_id=" + out_trade_no
            })
          },
          fail: function (res) {
            wx.hideLoading()
            that.setData({
              btnActive: true
            })
            return Util.Tips({
              title: "取消支付成功",
              // icon: "success"
            }, {
              tab: 5,
              url: "../order/detail?order_id=" + out_trade_no
            });
          }
        })
      }).catch(errmsg => {
      Util.Tips({title: errmsg})
    }).finally(() => {
      that.setData({
        btnActive: true
      })
      wx.hideLoading()
    })

  },

  onLoadTabbar: function () {//底部tabbar返回数据
    const that = this

    Util.checkIphone().then(res => {//检查是否是iphone x/11等
      that.setData({isIphoneX: res})

      wx.createSelectorQuery().in(that).select('.weui-footer')
        .boundingClientRect(function (rect) {
          if (!rect) return;

          let bottom = parseInt(rect.height);
          if (that.data.isIphoneX) {
            bottom += 24;
          } else {
            bottom += 15;
          }
          that.setData({
            bottom: bottom
          })
        }).exec()
    });
  },

});